import Vue from "vue";
import VueRouter from "vue-router";
import routes from "@/router/routes";
import { LoadingBar } from 'view-design';
import store from '@/store'
import _ from 'lodash'

Vue.use(VueRouter);

const router = new VueRouter({
  base: '/sentient/',
  routes
});

export default router;

const accessToken = () =>  _.get(store ,'state.app.access_token') || window.sessionStorage.getItem("dev:access_token")

router.beforeEach(async (to, from, next) => {
  // console.log('token: ',await accessToken());
  LoadingBar.start();
  let location
  if (await accessToken()) {
    if (to.name === 'login') {
      location = { name: 'main', replace: true }
    }
  } else {
    if (to.name !== 'login') {
      location = { name: 'login', replace: true }
    }
  }
  next(location)
})

router.afterEach(() => {
  LoadingBar.finish()
})

router.onError((error: TypeError) => {
  LoadingBar.error()
})
